package dm

import (
	"github.com/go-ole/go-ole"
	"time"
)

func (com *DmSoft) SetSimMode(mode int) int {
	ret, _ := com.dm.CallMethod("SetSimMode", mode)
	return int(ret.Val)
}

func (com *DmSoft) GetKeyState(vkCode int) int {
	ret, _ := com.dm.CallMethod("GetKeyState", vkCode)
	return int(ret.Val)
}

func (com *DmSoft) WaitKey(vkCode, timeOut int) int {
	ret, _ := com.dm.CallMethod("WaitKey", vkCode, timeOut)
	return int(ret.Val)
}
func (com *DmSoft) MoveTo(x, y int) int {
	ret, _ := com.dm.CallMethod("MoveTo", x, y)
	return int(ret.Val)
}

func (com *DmSoft) KeyPress(vkCode int) int {
	ret, _ := com.dm.CallMethod("KeyPress", vkCode)
	time.Sleep(30 * time.Microsecond)
	return int(ret.Val)
}

// LeftClick 按下鼠标左键
func (com *DmSoft) LeftClick() int {
	ret, _ := com.dm.CallMethod("LeftClick")
	return int(ret.Val)
}

func (com *DmSoft) MoveAndLeftClick(x, y int) int {
	com.MoveTo(x, y)
	time.Sleep(500 * time.Microsecond)
	ret, _ := com.dm.CallMethod("LeftClick")
	return int(ret.Val)
}

func (com *DmSoft) MoveAndLeftDoubleClick(x, y int) int {
	com.MoveTo(x, y)
	time.Sleep(100 * time.Microsecond)
	ret, _ := com.dm.CallMethod("LeftClick")
	ret, _ = com.dm.CallMethod("LeftClick")
	ret, _ = com.dm.CallMethod("LeftClick")
	return int(ret.Val)
}

func (com *DmSoft) RightClick() int {
	ret, _ := com.dm.CallMethod("RightClick")
	return int(ret.Val)
}

func (com *DmSoft) GetCursorPos() (int, int) {
	x := -1
	y := -1
	intx := ole.NewVariant(ole.VT_I4, int64(x))
	inty := ole.NewVariant(ole.VT_I4, int64(y))
	ret, _ := com.dm.CallMethod("GetCursorPos", &intx, &inty)
	if ret.Val <= 0 {
		return -1, -1
	}
	x = int(intx.Val)
	y = int(inty.Val)
	intx.Clear()
	inty.Clear()
	return x, y
}

// ListenKey 监听某个键是否被按下,按下期间一直执行method; 松开后返回
func (com *DmSoft) ListenKey(vkCode int, method func()) {
	com.WaitKey(vkCode, 0)
	for {
		state := com.GetKeyState(vkCode)
		if state == 0 {
			return
		}
		method()
	}
}

// ListenKeyUp 监听某个键是否被弹起,弹起时执行method
func (com *DmSoft) ListenKeyUp(vkCode int, method1 func(), method2 func()) {
	com.WaitKey(vkCode, 0)
	for {
		state := com.GetKeyState(vkCode)
		if state == 0 {
			method1()
			return
		}
		method2()
		duration, _ := time.ParseDuration("10ms")
		time.Sleep(duration)
	}
}
